<template>
  <div class="flow-main" style="background: white">
    <el-form
      ref="formFlowClassAIRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      :rules="rules"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <el-row :gutter="16">
        <el-col :span="12" v-if="!checkWidgetAuth('className', 'hide')">
          <el-form-item label="班级名称" prop="StudentClass.className">
            <el-input
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.StudentClass.className"
              type="text"
              placeholder=""
              :clearable="true"
              :show-word-limit="false"
              maxlength=""
              :disabled="checkWidgetAuth('className', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{formData.StudentClass.className}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!checkWidgetAuth('classLevel', 'hide')">
          <el-form-item label="班级级别" prop="StudentClass.classLevel">
            <el-select
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.StudentClass.classLevel"
              placeholder=""
              :clearable="true"
              :filterable="true"
              :disabled="checkWidgetAuth('classLevel', 'disabled')"
              @visible-change="classLevelWidget.onVisibleChange"
            >
              <el-option
                v-for="item in classLevelWidgetDropdownList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <span class="input-item input-label" v-else>{{(formData.StudentClass.classLevelDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!checkWidgetAuth('leaderId', 'hide')">
          <el-form-item label="班长" prop="StudentClass.leaderId">
            <el-select
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.StudentClass.leaderId"
              placeholder=""
              :clearable="true"
              :filterable="true"
              :disabled="checkWidgetAuth('leaderId', 'disabled')"
              @visible-change="leaderIdWidget.onVisibleChange"
            >
              <el-option
                v-for="item in leaderIdWidgetDropdownList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <span class="input-item input-label" v-else>{{(formData.StudentClass.leaderIdDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!checkWidgetAuth('schoolId', 'hide')">
          <el-form-item label="所属校区" prop="StudentClass.schoolId">
            <dept-select
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.StudentClass.schoolId"
              placeholder=""
              :disabled="checkWidgetAuth('schoolId', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{(formData.StudentClass.schoolIdDictMap || {}).name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!checkWidgetAuth('finishClassHour', 'hide')">
          <el-form-item label="完成课时" prop="StudentClass.finishClassHour">
            <el-input-number
              v-if="!props.readOnly && !taskReadOnly"
              class="input-item"
              v-model="formData.StudentClass.finishClassHour"
              placeholder=""
              :clearable="true"
              :step="1"
              :controls="true"
              :disabled="checkWidgetAuth('finishClassHour', 'disabled')"
            />
            <span class="input-item input-label" v-else>{{formData.StudentClass.finishClassHour}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!checkWidgetAuth('student', 'hide')">
          <table-box
            ref="student"
            :data="studentWidgetDataList"
            style="height: 500px"
            :size="layoutStore.defaultFormItemSize"
            :row-config="{isCurrent: false, isHover: true}"
            :seq-config="{startIndex: ((studentWidgetCurrentPage - 1) * studentWidgetPageSize)}"
            :sort-config="{remote: false}"
            :hasExtend="true"
            @refresh="studentWidget.refreshTable()"
          >
            <template #operator>
              <el-button
                v-if="!props.readOnly && !taskReadOnly"
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                @click="onFormFlowSetClassStudentAIClick()"
                >
                设置班级学生
              </el-button>
            </template>
            <vxe-column title="序号" type="seq" fixed="left" :index="studentWidget.getTableIndex" :width="80" />
            <vxe-column title="学生姓名" field="studentName" />
            <vxe-column title="所属校区" field="schoolIdDictMap.name" />
            <vxe-column title="所属年级" field="gradeIdDictMap.name" />
            <vxe-column title="经验等级" field="experienceLevelDictMap.name" />
            <vxe-column title="注册时间" field="registerTime">
              <template v-slot="scope">
                <span>{{formatDateByStatsType(scope.row.registerTime, 'day')}}</span>
              </template>
            </vxe-column>
            <vxe-column v-if="!props.readOnly && !taskReadOnly" title="操作" fixed="right">
              <template v-slot="scope">
                <el-button
                  link
                  type="primary"
                  :size="layoutStore.defaultFormItemSize"
                  @click.stop="onDeleteStudentClick(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </vxe-column>
            <template slot="empty">
              <div class="table-empty unified-font">
                <img src="@/assets/img/empty.png">
                <span>暂无数据</span>
              </div>
            </template>
          </table-box>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formFlowClassAI',
};
</script>

<script setup lang="ts">
import { useFlowAction } from '@/pages/workflow/handlerFlowTask/hook';
import { IProp } from '@/pages/workflow/handlerFlowTask/types';
import { FlowOperationController } from '@/api/flow';
import { SysFlowTaskOperationType } from '@/common/staticDict/flow';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useMessage, useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { StudentController, StudentClassController, CourseController, SysDeptController } from '@/api/generated';
import FormFlowSetClassStudentAI from '@/pages/workflow/pages/flowAddClass/formFlowSetClassStudentAI.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const processDefinitionKey = 'flowAddClass';

interface IFlowAddClassProps extends IProp {
  readOnly?: boolean | string;
  // 是否运行时任务
  isRuntimeTask?: boolean | string;
  // 是否草稿
  isDraft?: boolean | string;
  // 流程实例id
  processInstanceId?: string;
  // 抄送消息id
  messageId?: string;
  // 当前任务实例id
  taskId?: string;
  // 任务变量列表
  taskVariableList?: ANY_OBJECT[];
  // 委托人
  delegateUserId?: string;
};

const props = withDefaults(defineProps<IFlowAddClassProps>(), {
  readOnly: false,
  isRuntimeTask: false,
  isDraft: false,
  processInstanceId: undefined,
  taskId: undefined,
  messageId: undefined,
  taskVariableList: () => [],
});

const taskReadOnly = ref(true);

const formFlowClassAIRef = ref();
// 表单数据定义
type FormFlowClassAIData = {
  StudentClass: StudentClassData;
};
// 表单数据
const formData = reactive<FormFlowClassAIData>({
  StudentClass: {
    // 班级Id
    classId: undefined,
    // 班级名称
    className: undefined,
    // 所属校区
    schoolId: undefined,
    // 班长
    leaderId: undefined,
    // 完成课时
    finishClassHour: undefined,
    // 班级级别
    classLevel: undefined,
    // 创建用户
    createUserId: undefined,
    // 班级创建时间
    createTime: undefined,
    // 班级状态(0: 正常 1: 解散)
    status: undefined,
    // 班级课程数据
    courseList: [],
    // 学生管理数据
    studentList: [],
    sysDept: {
      // 部门Id
      deptId: undefined,
      // 部门名称
      deptName: undefined,
      // 显示顺序
      showOrder: undefined,
      // 父部门Id
      parentId: undefined,
      // 删除标记(1: 正常 -1: 已删除)
      deletedFlag: undefined,
      // 创建者Id
      createUserId: undefined,
      // 更新者Id
      updateUserId: undefined,
      // 创建时间
      createTime: undefined,
      // 更新时间
      updateTime: undefined,
    },
  },
},
);
// 表单验证规则
const rules = reactive({
  'StudentClass.schoolId': [
    {required: true, message: '请输入所属校区', trigger: 'blur'}
  ],
  'StudentClass.className': [
    {required: true, message: '请输入班级名称', trigger: 'blur'}
  ],
  'StudentClass.leaderId': [
    {required: true, message: '请输入班长', trigger: 'blur'}
  ],
  'StudentClass.classLevel': [
    {required: true, message: '请输入班级级别', trigger: 'blur'}
  ],
  'StudentClass.finishClassHour': [
    {required: true, message: '请输入完成课时', trigger: 'blur'},
    {type: 'integer', message: '完成课时只允许输入整数', trigger: 'blur', transform: (value) => Number(value)},
    {type: 'number', min: 0, message: '完成课时必须大于0', trigger: 'blur', transform: (value) => Number(value)},
  ],
});
const instance = getCurrentInstance();

const draftProcessInstanceId = ref<number | string | undefined>();
const draftTaskId = ref<number | string | undefined>();

const { preHandlerOperation, submitConsign } = useFlowAction(props);
const messageStore = useMessage();

const isStartFlow = computed(() => {
  return props.processInstanceId == null;
});

const isDraft = computed(() => {
  return typeof props.isDraft === 'string' ? props.isDraft === 'true' : props.isDraft;
});

const isRuntime = computed(() => {
  return typeof props.isRuntimeTask === 'string' ? props.isRuntimeTask === 'true' : props.isRuntimeTask;
});

// 撤销任务
const revokeTask = (operation: ANY_OBJECT) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm('是否撤销此任务？', '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(res => {
        return FlowOperationController.revokeHistoricTask({
          processInstanceId: props.processInstanceId,
          taskId: props.taskId,
          taskComment: '任务处理人撤销任务',
          taskVariableData: {
            latestApprovalStatus: operation.latestApprovalStatus
          },
          delegateUserId: props.delegateUserId
        });
      })
      .then(res => {
        resolve(res);
      })
      .catch(e => {
        return reject(e);
      });
  });
};
// 保存草稿
const handlerDraft = () => {
  return new Promise<void>((resolve, reject) => {
    let formData = getFormDataImpl();
    let params: ANY_OBJECT = {
      processDefinitionKey: processDefinitionKey,
      processInstanceId: props.processInstanceId || draftProcessInstanceId.value,
      studentClassDto: {
        ...formData.masterData
      },
      ...formData.relationData
    }
    StudentClassController.startAndSaveDraftFlowAddClass(params).then(res => {
      ElMessage.success('草稿保存成功！');
      draftProcessInstanceId.value = (res.data as ANY_OBJECT).processInstanceId;
      draftTaskId.value = (res.data as ANY_OBJECT).taskId;
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
// 获取表单数据
const getFormDataImpl = () => {
  // 一对一、一对多、多对多关联数据
  let relationData: ANY_OBJECT = {};
  relationData.classStudentDtoList = studentWidgetDataList.value.map(item => {
    return {
      studentId: item.studentId
    }
  });
  return {
    masterData: {
      ...formData.StudentClass
    },
    relationData: relationData
  }
};
// 获取流程表单数据
const getMasterData = (operationType: string, assignee: string | Array<string> | undefined) => {
  let taskVariableData;
  if (Array.isArray(props.taskVariableList) && props.taskVariableList.length > 0) {
    taskVariableData = props.taskVariableList.reduce((retObj, item) => {
      if (item.variableType === 0) {
        // 固定值
        retObj[item.variableName] = item.variableValue;
      } else if (item.variableType === 1) {
        // 字段值
        retObj[item.variableName] = formData.TestFlowContract[item.variableValue] || '';
      }
      return retObj;
    }, {});
  }
  // 会签操作设置多实例处理人集合
  assignee = (assignee && assignee !== '') ? (assignee as string).split(',') : undefined;
  if (operationType === StaticDict.SysFlowTaskOperationType.MULTI_SIGN) {
    if (taskVariableData == null) taskVariableData = {};
    taskVariableData.assigneeList = assignee;
  } else if (operationType === StaticDict.SysFlowTaskOperationType.SET_ASSIGNEE) {
    if (taskVariableData == null) taskVariableData = {};
    taskVariableData.appointedAssignee = Array.isArray(assignee) ? assignee.join(',') : undefined;
  }

  return {
    ...getFormDataImpl(),
    taskVariableData
  }
};
// 启动流程
const handlerStart = (operation: ANY_OBJECT, copyItemList: Array<ANY_OBJECT>, xml?: string | undefined) => {
  // 启动并保存草稿后再次提交
  if (draftProcessInstanceId.value != null && draftTaskId.value != null) {
    return handlerOperation(operation, copyItemList);
  }
  return new Promise<void>((resolve, reject) => {
    formFlowClassAIRef.value.validate((valid: boolean) => {
      if (!valid) return reject();
      preHandlerOperation(operation, true, xml).then(res => {
        let formData = getMasterData(operation.type, (res || {}).assignee);
        let tempVariableData;
        if (operation.variableList != null && operation.variableList !== '') {
          if (typeof operation.variableList === 'string') {
            try {
              tempVariableData = JSON.parse(operation.variableList);
            } catch (e) {
              console.error(e);
            }
          } else {
            tempVariableData = operation.variableList;
          }
        }
        return StudentClassController.startAndTakeUserTaskFlowAddClass({
          processDefinitionKey: processDefinitionKey,
          taskVariableData: {
            ...formData.taskVariableData,
            ...tempVariableData,
            latestApprovalStatus: operation.latestApprovalStatus
          },
          flowTaskCommentDto: {
            approvalType: operation.type
          },
          studentClassDto: {
            ...formData.masterData
          },
          ...formData.relationData,
          copyData: (copyItemList || []).reduce((retObj, item) => {
            retObj[item.type] = item.id;
            return retObj;
          }, {})
        });
      }).then(res => {
        ElMessage.success('启动成功！');
        resolve();
      }).catch(e => {
        reject(e);
      });
    });
  });
};
// 流程操作
const handlerOperation = (operation: ANY_OBJECT, copyItemList:Array<ANY_OBJECT>, xml?: string | undefined) => {
  return new Promise<void>((resolve, reject) => {
    formFlowClassAIRef.value.validate(valid => {
      if (!valid) return reject();
      preHandlerOperation(operation, isDraft.value, xml).then(res => {
        // 加签、减签操作
        if (
          [
            SysFlowTaskOperationType.CO_SIGN,
            SysFlowTaskOperationType.SIGN_REDUCTION,
            SysFlowTaskOperationType.BFORE_CONSIGN,
            SysFlowTaskOperationType.AFTER_CONSIGN,
          ].includes(operation.type)
        ) {
          // 串行会签前后加签参数
          let before;
          if (
            operation.type === SysFlowTaskOperationType.BFORE_CONSIGN ||
            operation.type === SysFlowTaskOperationType.AFTER_CONSIGN
          ) {
            before = operation.type === SysFlowTaskOperationType.BFORE_CONSIGN;
          }
          return submitConsign((res || {}).assignee, operation.type === SysFlowTaskOperationType.CO_SIGN, before);
        }
        // 自由跳
        if (operation.type === StaticDict.SysFlowTaskOperationType.FREE_JUMP) {
          return FlowOperationController.freeJump({
            processInstanceId: props.processInstanceId,
            sourceTaskId: props.taskId,
            targetTaskKey: (res || {}).targetTaskKey,
            delegateAssignee: (res || {}).assignee,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 驳回操作
        if (
          operation.type === StaticDict.SysFlowTaskOperationType.REJECT ||
          operation.type === StaticDict.SysFlowTaskOperationType.REJECT_TO_TASK
        ) {
          return FlowOperationController.rejectRuntimeTask({
            processInstanceId: props.processInstanceId,
            taskId: props.taskId,
            targetTaskKey: (res || {}).targetTaskKey,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 驳回到起点
        if (operation.type === StaticDict.SysFlowTaskOperationType.REJECT_TO_START) {
          return FlowOperationController.rejectToStartUserTask({
            processInstanceId: props.processInstanceId,
            taskId: props.taskId,
            taskComment: (res || {}).message,
            taskVariableData: {
              latestApprovalStatus: operation.latestApprovalStatus
            },
            delegateUserId: props.delegateUserId
          });
        }
        // 撤销操作
        if (operation.type === StaticDict.SysFlowTaskOperationType.REVOKE) {
          return revokeTask(operation);
        }
        let formData = getMasterData(operation.type, (res || {}).assignee);
        let params: ANY_OBJECT = {
          taskId: props.taskId || draftTaskId.value,
          processInstanceId: props.processInstanceId || draftProcessInstanceId.value,
          delegateUserId: props.delegateUserId,
          flowTaskCommentDto: {
            taskComment: (res || {}).message,
            approvalType: operation.type,
            delegateAssignee: operation.type === StaticDict.SysFlowTaskOperationType.TRANSFER ? (res || {}).assignee : undefined,
          },
          taskVariableData: {
            ...formData.taskVariableData,
            latestApprovalStatus: operation.latestApprovalStatus
          },
          copyData: (copyItemList || []).reduce((retObj, item) => {
            retObj[item.type] = item.id;
            return retObj;
          }, {})
        }
        // 非只读状态下，提交修改数据
        if (!taskReadOnly.value) {
          // 主表数据
          params.studentClassDto = {
            ...formData.masterData
          };
          // 关联数据
          params = {
            ...params,
            ...formData.relationData
          };
        }

        let tempVariableData;
        if (operation.variableList != null && operation.variableList !== '') {
          if (typeof operation.variableList === 'string') {
            try {
              tempVariableData = JSON.parse(operation.variableList);
            } catch (e) {
              console.error(e);
            }
          } else {
            tempVariableData = operation.variableList;
          }
        }
        if (tempVariableData != null) {
          params.taskVariableData = {
            ...params.taskVariableData,
            ...tempVariableData,
          };
        }

        return StudentClassController.submitUserTaskFlowAddClass(params);
      }).then(res => {
        messageStore.reloadMessage();
        if (operation.type !== StaticDict.SysFlowTaskOperationType.CO_SIGN && operation.type !== StaticDict.SysFlowTaskOperationType.SIGN_REDUCTION) {
         ElMessage.success(operation.label + '成功！');
        }
        resolve();
      }).catch(e => {
        console.log(e);
      });
    });
  });
};

/**
 * 班级级别下拉数据获取函数
 */
const loadClassLevelDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 班级级别配置参数
const classLevelOptions: DropdownOptions<DictData> = {
  loadData: loadClassLevelDropdownList,
  isTree: false,
};
// 班级级别下拉组件
const classLevelWidget = useDropdown(classLevelOptions);
const { dropdownList: classLevelWidgetDropdownList } = classLevelWidget
/**
 * 班长下拉数据获取函数
 */
const loadLeaderIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictStudent(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 班长配置参数
const leaderIdOptions: DropdownOptions<DictData> = {
  loadData: loadLeaderIdDropdownList,
  isTree: false,
};
// 班长下拉组件
const leaderIdWidget = useDropdown(leaderIdOptions);
const { dropdownList: leaderIdWidgetDropdownList } = leaderIdWidget
/**
 * 学生管理数据获取函数，返回Promise
 */
const loadStudentWidgetData = (params: ANY_OBJECT) => {
  return new Promise((resolve, reject) => {
    // 级联更新设置临时唯一id
    let tempTime = new Date().getTime();
    let tableData = {
      dataList: formData.StudentClass.studentList.map(item => {
        return {
          ...item,
          __cascade_add_temp_id__: tempTime++
        };
      }),
      totalCount: formData.StudentClass.studentList.length
    };
    resolve(tableData);
  });
};
/**
 * 学生管理数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentVerify = () => {
  return true;
};
/**
 * 设置班级学生
 */
const onFormFlowSetClassStudentAIClick = (row?: StudentData) => {
  let params = {
    classId: formData.StudentClass.classId,
    saveOnSubmit: false,
    selectIdList: studentWidgetDataList.value.map(item => item.studentId)
  };

  Dialog
    .show(
      '设置班级学生',
      FormFlowSetClassStudentAI,
      { area: ['1200px', '90px'] },
      params
    )
    .then(res => {
      if (Array.isArray(res)) {
        let tempTime = new Date().getTime();
        studentWidgetDataList.value.push(
          ...res.map((item, index) => {
            return {
              ...item,
              // 级联添加每次添加后并不保存到数据库，设置临时的唯一值
              __cascade_add_temp_id__: tempTime + index
            };
          })
        );
        formData.StudentClass.studentList = studentWidgetDataList.value;
      }
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 删除
 */
const onDeleteStudentClick = (row?: StudentData) => {
  ElMessageBox.confirm('是否删除选中数据？').then(res => {
    studentWidgetDataList.value = studentWidgetDataList.value.filter(item => {
      return item.__cascade_add_temp_id__ !== row?.__cascade_add_temp_id__;
    });
    formData.StudentClass.studentList = studentWidgetDataList.value;
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 学生管理表格组件参数
const studentOptions: TableOptions<StudentData> = {
  loadTableData: loadStudentWidgetData,
  verifyTableParameter: loadStudentVerify,
  paged: false,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 学生管理表格组件
const student = ref();
const studentWidget = useTable(studentOptions);
const {
  dataList: studentWidgetDataList,
  currentPage: studentWidgetCurrentPage,
  pageSize: studentWidgetPageSize,
  totalCount: studentWidgetTotalCount,
} = studentWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
/**
 * 重置过滤值
 */
const resetFormFlowClassAI = () => {
  refreshFormFlowClassAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormFlowClassAI();
};
const refreshFormFlowClassAI = () => {
  // 刷新段落
  studentWidget.refreshTable();
};
// 初始化流程表单
const initFormData = () => {
  if (!isStartFlow.value) {
    // 流程办理
    let params: ANY_OBJECT = {
      processInstanceId: props.processInstanceId,
      taskId: props.taskId,
      delegateUserId: props.delegateUserId,
    }
    let httpCall: ANY_OBJECT | null = null;
    if (isDraft.value) {
      // 草稿数据
      httpCall = FlowOperationController.viewDraftData({
        processDefinitionKey: processDefinitionKey,
        processInstanceId: props.processInstanceId
      });
    } else if (props.messageId != null) {
      // 抄送消息
      httpCall = FlowOperationController.viewCopyBusinessData({
        messageId: props.messageId
      });
    } else {
      httpCall = (props.taskId && isRuntime.value) ? StudentClassController.viewTaskBusinessDataFlowAddClass(params) : StudentClassController.viewHistoricTaskBusinessDataFlowAddClass(params)
    }
    httpCall.then(res => {
      formData.StudentClass = { ...res.data };
      if (formData.StudentClass.sysDept == null) {
        formData.StudentClass.sysDept = {
          deptId: undefined,
          deptName: undefined,
          showOrder: undefined,
          parentId: undefined,
          deletedFlag: undefined,
          createUserId: undefined,
          updateUserId: undefined,
          createTime: undefined,
          updateTime: undefined
        };
      }
      studentWidget.refreshTable();
      classLevelWidget.onVisibleChange(true).catch(e => {console.error(e)});
      leaderIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
      refreshFormFlowClassAI();
    }).catch(e => {
      // 异常处理
      console.log(e);
    });
  } else {
    // 启动流程
    classLevelWidget.onVisibleChange(true).catch(e => {console.error(e)});
    leaderIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    refreshFormFlowClassAI();
  }
};

const formAuth = ref<ANY_OBJECT>({});
const formAuthData = computed(() => {
  return (formAuth.value || {}).pc;
});

const checkWidgetAuth = (variableName: string, authType) => {
  console.log(formAuthData.value, variableName);
  if (formAuthData.value == null || formAuthData.value[variableName] == null) {
    return false;
  }
  let authItem = formAuthData.value[variableName];
  if (authType === 'disabled') {
    return authItem.disabled;
  } else if (authType === 'hide') {
    return authItem.hide;
  }
  return false;
};

const viewTaskFormKey = () => {
  return new Promise((resolve, reject) => {
    FlowOperationController.viewTaskFormKey({
      processDefinitionKey: processDefinitionKey,
      processInstanceId: props.processInstanceId,
      taskId: props.taskId
    })
      .then(res => {
        let temp = JSON.parse(res.data);
        taskReadOnly.value = temp.readOnly == null ? true : temp.readOnly;
        formAuth.value = temp.formAuth;
        Object.keys(formAuth.value || {}).forEach(key => {
          let formAuthItem = formAuth.value[key];
          Object.keys(formAuthItem).forEach(subKey => {
            let authItem = formAuthItem[subKey];
            if (authItem && authItem != null && authItem !== '') {
              formAuthItem[subKey] = authItem.split(',').map(item => parseInt(item));
            } else {
              formAuthItem[subKey] = [0, 0];
            }
            let disabled = formAuthItem[subKey][0] === 1;
            let hide = formAuthItem[subKey][1] === 1;
            formAuthItem[subKey].disabled = disabled;
            formAuthItem[subKey].hide = hide;
          });
        });
        resolve(res);
      })
      .catch(e => {
        reject(e);
      });
  });
};

onMounted(() => {
  viewTaskFormKey().then(() => {
    initFormData();
  }).catch(e => {
    console.log(e);
  });
});

defineExpose({
  handlerStart,
  handlerOperation,
  handlerDraft,
  initFormData,
  getMasterData,
});
</script>

<style scoped>
.flow-main {
  display: flex;
  flex-direction: column;
  background: #F6F7F9;
}
</style>